package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author hyj
 * @create 2023--11--09
 */
@Component
public class RedisIdWorker {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 开始时间戳 -->2023,1.1,0,0,0
     */
    private static final long BEGIN_TIMESTAMP = 1672531200;

    /**
     * 时间戳移动位数
     */
    private static final int COUNT_BITS = 32;

    /**
     * 生成全局唯一ID
     * @param keyPrefix
     * @return
     */
    public long nextId(String keyPrefix){

        //生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long second = now.toEpochSecond(ZoneOffset.UTC);
        long time = second - BEGIN_TIMESTAMP;

        //生成序列号
        //获取当天日期
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //自增
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);

        //拼接返回
        return time << COUNT_BITS | count;
    }

}
